package com.asiainfo.demo.dao.proxy;

import com.asiainfo.demo.dao.dbcon.IYogaCon;
import com.asiainfo.demo.dao.idao.iCard;
import com.asiainfo.demo.dao.impl.CardImpl;
import com.asiainfo.demo.dao.roles.Card;

import java.util.ArrayList;

public class CardProxy implements iCard {
    private IYogaCon con = null;
    private iCard cardDao = null;

    public CardProxy() throws Exception {
        con = new IYogaCon();
        cardDao = new CardImpl(con.getConnection());
    }

    @Override
    public boolean insertCard(Card card) throws Exception {
        boolean flag = false;

        if (cardDao.findCardByID(card.getCardID()) == null) {
            try {
                flag = cardDao.insertCard(card);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Primary Key Exists. Insert Failed.");
        }

        con.close();
        return flag;
    }

    @Override
    public Card findCardByID(int cardID) throws Exception {
        Card card = cardDao.findCardByID(cardID);
        con.close();
        return card;
    }

    @Override
    public ArrayList<Card> findAllCards() throws Exception {
        ArrayList<Card> cards = cardDao.findAllCards();
        con.close();

        return cards;
    }

    @Override
    public int findMaxCardID() throws Exception {
        int maxCardID = cardDao.findMaxCardID();
        con.close();

        return maxCardID;
    }

    @Override
    public boolean changeValid(int cardID, byte newStatus) throws Exception {
        boolean flag = false;

        if (cardDao.findCardByID(cardID) != null) {
            try {
                flag = cardDao.changeValid(cardID, newStatus);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        con.close();

        return flag;
    }

    @Override
    public boolean changeType(int cardID, byte newType) throws Exception {
        boolean flag = false;

        if (cardDao.findCardByID(cardID) != null) {
            try {
                flag = cardDao.changeType(cardID, newType);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        con.close();

        return flag;
    }
}
